import axios from 'axios';
import { LOCAL_KEY } from '@/constant/dict';
import qs from 'qs';
import router from '@/router';

let isRefreshing = false;
let refreshSubscribers = [];

function subscribeTokenRefresh(cb) {
  refreshSubscribers.push(cb);
}

function onRefreshed(newToken) {
    console.log('onRefreshed:', newToken,refreshSubscribers);
  refreshSubscribers.forEach(cb => cb(newToken));
  refreshSubscribers = [];
}

// 创建axios实例
const service = axios.create({
    timeout: 30000,
    withCredentials: true,
    // baseURL: "http:///192.168.3.25:8080",
    headers: {
        // 'Content-Type': 'application/json,charset=UTF-8',
        'Content-Type': 'application/x-www-form-urlencoded',
        // 'Access-Control-Allow-Origin': '*',
    }
});

//'Access-Control-Allow-Origin': '*',

// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
// axios.defaults.timeout = 35000;
// axios.defaults.withCredentials = true;
// axios.defaults.baseURL = "http:///192.168.3.224:8080";

service.interceptors.request.use((config) => {
    // 从本地存储获取token
    const token = localStorage.getItem(LOCAL_KEY.IS_AUTH_TOKEN);
    if (token) {
      config.headers.Authorization = `${token}`;
    }

    // 序列号post 参数，解决post 参数为对象时，后端接收为null的问题
    const contentType = config.headers['Content-Type'] || config.headers['content-type'];
    if (config.method === 'post' 
        && contentType && contentType.includes('application/x-www-form-urlencoded')  
        && config.data && typeof config.data === 'object' ) {
        // 序列化逻辑
        config.data = qs.stringify(config.data);
    }
    
    // 添加请求时间戳
    config._requestStartTime = Date.now();
    return config;  // 返回处理后的配置
}, error => {
    // 请求配置阶段发生错误时的处理逻辑
    console.error('请求拦截器错误:', error);
    return Promise.reject(error);
  });

service.interceptors.response.use((response) => {

    if (response.config._requestStartTime) {
      const cost = Date.now() - response.config._requestStartTime;
      const api = response.config.url;
      console.log(`${api} 请求耗时: ${cost}ms`);
    }

    // 后端返回格式为 { code: 0, data: {...}, message: '' }
    let {code = -1,message = "",data = ""} = response.data;
    if (code === 0) {
        console.log('return data =',data);
      return data;
    } else {
      return Promise.reject({
        code: code,
        message: message,
        response  // 保留原始响应以便调试,争对不同的错误类型进行处理
      });
    }
}, async error => {
    let {config, response} = error;
    const status = response?.status;
    if (status && status === 401 && config.url !== '/api/auth/refresh') {
      const retryOriginalRequest = new Promise((resolve) => {
        subscribeTokenRefresh(token => {
            config.headers.Authorization = `${token}`;
            resolve(service(config));
        });
      });

      if (!isRefreshing) {
        isRefreshing = true;
        try {
          // 调用刷新接口（Cookie 自动携带）
          const refreshRes = await service.post('/api/auth/refresh');
          
          const newAccessToken = refreshRes.token;
          // 更新本地存储
          localStorage.setItem(LOCAL_KEY.IS_AUTH_TOKEN, newAccessToken);

          isRefreshing = false;
          onRefreshed(newAccessToken);
          // 重试原请求
          return retryOriginalRequest;
        } catch (refreshError) {
          // 刷新失败，登出
          localStorage.removeItem(LOCAL_KEY.IS_AUTH_TOKEN);
          router.replace('/login'); // 或跳转登录页
          return Promise.reject(refreshError);
        }
      }
      // 多个请求同时 401，排队等待
      return retryOriginalRequest;
    }
    if (error.response) {
      const { code, data } = error.response;
      switch (code) {
        case 401:  // 未授权、需要跳转到登录页面
          localStorage.removeItem(LOCAL_KEY.IS_AUTH_TOKEN);
          router.replace('/login');
          break;
        case 403:
          console.error('权限不足', data);
          break;
        case 404:
          // 判断请求路径是否以/api开头
          if (!error.config.url.startsWith('/api')) {
        router.replace('/404');
        break;
          }
          console.error('请求的资源不存在', data);
          break;
        case 500:
          console.error('服务器内部错误', data);
          break;
        default:
          console.error(`未预期的错误: ${code}`, data);
      }
    } else if (error.request) {
      // 请求已发送但未收到响应
      console.error('网络错误，未收到响应', error.request);
    } else {
      // 请求配置有误
      console.error('请求配置错误', error.message);
    }
    // 将错误继续向下传递
    return Promise.reject(error);
  });

export default service;
